package util

import (
	"io/ioutil"
	"net/http"
	"strings"
)
type curl struct {
	url string
	body string
	header map[string]string
}
/**
	设置header头
 */
func (c *curl)Header(h map[string]string) *curl{
	c.header = h
	return c
}
/**
	传输数据
 */
func (c *curl)Body(jsonStr string) *curl{
	c.body = jsonStr
	return c
}
func (c *curl)Url(url string) *curl{
	c.url = url
	return c
}
/**

 */
func (c *curl)GET() (string,error){

	req, err := http.NewRequest("GET", c.url, nil)
	if err != nil{
		return "",nil
	}
	if c.header != nil{
		for key,val := range c.header{
			req.Header.Add(key,val)
		}
	}

	res, err := http.DefaultClient.Do(req)
	if err !=nil {
		return "",nil
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil{
		return "",err
	}

	return string(body),nil
}
func (c *curl)POST() (string,error){

	payload := strings.NewReader(c.body)

	req, err := http.NewRequest("POST", c.url, payload)
	if err != nil{
		return "",err
	}

	if c.header != nil{
		for key,val := range c.header{
			req.Header.Add(key,val)
		}
	}

	res, err := http.DefaultClient.Do(req)
	if err != nil{
		return "",err
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil{
		return "",err
	}
	return string(body),nil

}
func (c *curl)PUT() (string,error){

	payload := strings.NewReader(c.body)

	req, err := http.NewRequest("PUT", c.url, payload)
	if err != nil{
		return "",err
	}
	if c.header != nil{
		for key,val := range c.header{
			req.Header.Add(key,val);
		}
	}

	res, err := http.DefaultClient.Do(req)
	if err != nil{
		return "",err
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil{
		return "",err
	}

	return string(body),nil
}
func (c *curl)DELETE() (string,error){

	req, err := http.NewRequest("DELETE", c.url, nil)
	if err != nil{
		return "",err
	}
	if c.header != nil{
		for key,val := range c.header{
			req.Header.Add(key, val)
		}
	}

	res, err := http.DefaultClient.Do(req)
	if err != nil{
		return "",err
	}

	defer res.Body.Close()
	body, err := ioutil.ReadAll(res.Body)
	if err != nil{
		return "",err
	}

	return string(body),nil
}
var Curl = &curl{}

